package cn.line5.organization;

import java.util.List;
import java.util.Map;

import cn.line5.seam.annotations.Name;
import cn.line5.seam.db.PageResult;
import cn.line5.seam.db.QueryFactory;

@Name("organizationDao")
/**
 * <h1>机构用户数据库实现类</h1>
 * <br/>
 * 
 * @author Liu,Xiaojun
 */
public class OrganizationDaoImpl implements OrganizationDao {

	private final String organizationSql = "SELECT ORGANIZATION_ID as organizationId, ORGANIZATION_NAME as organizationName, ORGANIZATION_EN_NAME as organizationEnName, ORGANIZATION_CODE as organizationCode, PHONE as phone, ADDRESS as address, ZIPCODE as zipcode, MANAGER as manager, ORGANIZATION_SORT as organizationSort  FROM T_ORGANIZATION";

	private final String userSql = "SELECT USER_ID as userId, ORGANIZATION_ID as organizationId, LOGIN_NAME as loginName, LOGIN_PASSWORD as loginPassword, REAL_NAME as realName, GENDER as gender, PHOTO_URL as photoUrl, POSITION as position, EDUCATION as education, PHONE as phone, MOBILE_PHONE as mobilePhone, EMAIL as email, CREATE_TIME as createTime, LAST_LOGIN_TIME as lastLoginTime, LOGIN_NUM as loginNum, STATUS as status FROM T_USER";

	/**
	 * 查询子机构列表
	 */
	public List<OrganizationVo> getOrganizationList(String parentId) {
		return QueryFactory
				.createQuery(
						organizationSql
								+ " WHERE ORGANIZATION_ID LIKE ? ORDER BY ORGANIZATION_SORT")
				.setParameter(1, parentId + "___").list(OrganizationVo.class);
	}

	/**
	 * 查询子机构分页列表
	 */
	public PageResult<OrganizationVo> getOrganizationPageList(String parentId,
			int currentPage) {
		return QueryFactory
				.createQuery(
						organizationSql
								+ " WHERE ORGANIZATION_ID LIKE ? ORDER BY ORGANIZATION_SORT")
				.setParameter(1, parentId + "___").setCurrentPage(
						currentPage > 0 ? currentPage : 1).setPageRows(
						OrganizationConstants.PAGE_ROWS).pageList(
						OrganizationVo.class);
	}

	/**
	 * 查询机构信息
	 */
	public OrganizationVo getOrganization(String organizationId) {
		return QueryFactory.createQuery(
				organizationSql + " WHERE ORGANIZATION_ID=?").setParameter(1,
				organizationId).single(OrganizationVo.class);
	}

	/**
	 * 获取同级机构最大ID
	 */
	public String getOrganizationMaxId(String parentId) {
		Map<String, Object> m = QueryFactory
				.createQuery(
						"SELECT MAX(ORGANIZATION_ID) as maxid FROM T_ORGANIZATION WHERE ORGANIZATION_ID LIKE ?")
				.setParameter(1, parentId + "___").single();
		if (m != null && m.containsKey("maxid") && m.get("maxid") != null)
			return (String) m.get("maxid");
		else
			return parentId + "000";
	}

	/**
	 * 获取同级机构最大排序
	 */
	public Integer getOrganizationMaxSort(String parentId) {
		Map<String, Object> m = QueryFactory
				.createQuery(
						"SELECT MAX(ORGANIZATION_SORT) as maxsort FROM T_ORGANIZATION WHERE ORGANIZATION_ID LIKE ?")
				.setParameter(1, parentId + "___").single();
		if (m != null && m.containsKey("maxsort") && m.get("maxsort") != null)
			return (Integer) m.get("maxsort");
		else
			return 0;
	}

	/**
	 * 添加机构
	 */
	public Boolean addOrganization(OrganizationVo vo) {
		return QueryFactory
				.createExecute(
						"INSERT INTO T_ORGANIZATION VALUES(:organizationId, :organizationName, :organizationEnName, :organizationCode, :phone, :address, :zipcode, :manager, :organizationSort)",
						vo).execute() > 0;
	}

	/**
	 * 修改机构
	 */
	public Boolean modifyOrganization(OrganizationVo vo) {
		return QueryFactory
				.createExecute(
						"UPDATE T_ORGANIZATION SET ORGANIZATION_NAME=:organizationName, ORGANIZATION_EN_NAME=:organizationEnName, organization_Code=:organizationCode, phone=:phone, address=:address , zipcode=:zipcode, manager=:manager WHERE ORGANIZATION_ID=:organizationId",
						vo).execute() > 0;
	}

	/**
	 * 保存机构排序
	 */
	public Boolean saveOrganizationSort(OrganizationVo vo) {
		return QueryFactory
				.createExecute(
						"UPDATE T_ORGANIZATION SET ORGANIZATION_SORT=:organizationSort WHERE ORGANIZATION_ID=:organizationId",
						vo).execute() > 0;
	}

	/**
	 * 删除机构及子机构
	 */
	public Boolean deleteOrganization(String organizationId) {
		return QueryFactory.createExecute(
				"DELETE FROM T_ORGANIZATION WHERE ORGANIZATION_ID LIKE ?")
				.setParameter(1, organizationId + "%").execute() >= 0;
	}

	/**
	 * 查询用户分页列表
	 */
	public PageResult<UserVo> getUserPageList(String organizationId,
			int currentPage) {
		return QueryFactory
				.createQuery(
						userSql
								+ " WHERE ORGANIZATION_ID = ? ORDER BY CREATE_TIME DESC")
				.setParameter(1, organizationId).setCurrentPage(
						currentPage > 0 ? currentPage : 1).setPageRows(
						OrganizationConstants.PAGE_ROWS).pageList(UserVo.class);
	}

	/**
	 * 查询用户信息
	 */
	public UserVo getUser(String userId) {
		return QueryFactory.createQuery(userSql + " WHERE USER_ID=?")
				.setParameter(1, userId).single(UserVo.class);
	}

	/**
	 * 根据登录名查询用户信息
	 */
	public UserVo getUserByLoginName(String loginName) {
		return QueryFactory.createQuery(userSql + " WHERE LOGIN_NAME=?")
				.setParameter(1, loginName).single(UserVo.class);
	}

	/**
	 * 查询机构下的用户数量
	 */
	public Integer getUserCountByOrganizationId(String organizationId) {
		return QueryFactory.createQuery(
				"SELECT COUNT(*) FROM T_USER WHERE ORGANIZATION_ID like ?")
				.setParameter(1, organizationId + "%").count();
	}

	/**
	 * 添加用户
	 */
	public Boolean addUser(UserVo vo) {
		return QueryFactory
				.createExecute(
						"INSERT INTO T_USER VALUES(:userId, :organizationId, :loginName, :loginPassword, :realName, :gender, :photoUrl, :position, :education, :phone, :mobilePhone, :email, now(), now(), :loginNum, :status)",
						vo).execute() > 0;
	}

	/**
	 * 修改用户
	 */
	public Boolean modifyUser(UserVo vo) {
		return QueryFactory
				.createExecute(
						"UPDATE T_USER SET REAL_NAME=:realName, GENDER=:gender, PHOTO_URL=:photoUrl, POSITION=:position, EDUCATION=:education, PHONE=:phone, MOBILE_PHONE=:mobilePhone, EMAIL=:email WHERE USER_ID=:userId",
						vo).execute() > 0;
	}

	/**
	 * 修改用户密码
	 */
	public Boolean modifyLoginPassword(UserVo vo) {
		return QueryFactory
				.createExecute(
						"UPDATE T_USER SET LOGIN_PASSWORD=:loginPassword WHERE USER_ID=:userId",
						vo).execute() > 0;
	}

	/**
	 * 修改用户状态
	 */
	public Boolean modifyUserStatus(UserVo vo) {
		return QueryFactory.createExecute(
				"UPDATE T_USER SET STATUS=:status WHERE USER_ID=:userId", vo)
				.execute() > 0;
	}

	/**
	 * 修改用户登录次数
	 */
	public Boolean modifyLoginNum(UserVo vo) {
		return QueryFactory
				.createExecute(
						"UPDATE T_USER SET LAST_LOGIN_TIME=now(), LOGIN_NUM=:loginNum WHERE USER_ID=:userId",
						vo).execute() > 0;
	}

	/**
	 * 修改用户所属部门
	 */
	public Boolean modifyOrganization(UserVo vo) {
		return QueryFactory
				.createExecute(
						"UPDATE T_USER SET ORGANIZATION_ID=:organizationId WHERE USER_ID=:userId",
						vo).execute() > 0;
	}

	/**
	 * 删除用户
	 */
	public Boolean deleteUser(String userId) {
		return QueryFactory.createExecute(
				"DELETE FROM T_USER WHERE USER_ID = ?").setParameter(1, userId)
				.execute() >= 0;
	}

	/**
	 * 删除用户下的所有权限
	 */
	public Boolean removePermission(String userId) {
		return QueryFactory.createExecute(
				"DELETE FROM T_PERMISSION WHERE USER_ID = ?").setParameter(1,
				userId).execute() >= 0;
	}

	/**
	 * 添加用户权限
	 */
	public Boolean addPermission(PermissionVo vo) {
		return QueryFactory
				.createExecute(
						"INSERT INTO T_PERMISSION VALUES(:userId, :permissionId, :permissionType)",
						vo).execute() > 0;
	}

	/**
	 * 获取权限列表
	 */
	public List<PermissionVo> getPermissionList(PermissionVo vo) {
		StringBuffer sb = new StringBuffer(
				"SELECT USER_ID as userId, PERMISSION_ID as permissionId, PERMISSION_TYPE as permissionType FROM T_PERMISSION WHERE 1=1");
		if (vo.getUserId() != null && vo.getUserId().length() > 0)
			sb.append(" AND USER_ID=:userId");
		if (vo.getPermissionType() != null
				&& vo.getPermissionType().length() > 0)
			sb.append(" AND PERMISSION_TYPE=:permissionType");
		return QueryFactory.createQuery(sb.toString(), vo).list(
				PermissionVo.class);
	}
}